package com.ukao.steward.ui.valetRunners.createOrder;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ukao.steward.R;
import com.ukao.steward.adapter.ShoppListAdapter;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.ShoppingBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.dialog.ServeCarDialogFragment;
import com.ukao.steward.eventbus.ShoppChildEvent;
import com.ukao.steward.eventbus.ShoppEvent;
import com.ukao.steward.listener.DialogSubmitListener;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.L;
import com.ukao.steward.util.T;
import com.ukao.steward.widget.MyLRecyclerView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.ukao.steward.consts.Constant.ARG_PARAM10;
import static com.ukao.steward.consts.Constant.ARG_PARAM3;
import static com.ukao.steward.consts.Constant.ARG_PARAM4;
import static com.ukao.steward.consts.Constant.ARG_PARAM5;
import static com.ukao.steward.consts.Constant.ARG_PARAM6;
import static com.ukao.steward.consts.Constant.ARG_PARAM7;
import static com.ukao.steward.consts.Constant.ARG_PARAM8;
import static com.ukao.steward.consts.Constant.ARG_PARAM9;

/**
 * 商城子控件
 */
public class shoppListFragmentChild extends BaseFragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.line)
    View line;
    @BindView(R.id.recycler_views)
    MyLRecyclerView recyclerViews;
    Unbinder unbinder;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ShoppListAdapter mShoppListAdapter;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    View view;


   private   boolean   isloadFinish;
    private String typeiId;
    private String businessId;
    private String businessName;
    private ArrayList<ShoppingBean> mChageData;
    private boolean isValuationEnter;
    private View mEmptyView;
    private String userId;
    private boolean isStorageEnter;
    private String mercBusinessId;
    private boolean isOrderStockInEnter;
    private String orderId;

    public static shoppListFragmentChild newInstance(String typeiId, String businessId,String  businessName,
                                                     ArrayList<ShoppingBean>    mShoppingDate,
                                                     boolean isValuationEnter,String  userId,boolean isStorageEnter,
                                                     String mercBusinessId,boolean isOrderStockInEnter,String  orderId) {
        shoppListFragmentChild fragment = new shoppListFragmentChild();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, typeiId);
        args.putString(ARG_PARAM2, businessId);
        args.putString(ARG_PARAM3, businessName);
        args.putParcelableArrayList(ARG_PARAM4, mShoppingDate);
        args.putBoolean(ARG_PARAM5, isValuationEnter);
        args.putString(ARG_PARAM6, userId);
        args.putBoolean(ARG_PARAM7, isStorageEnter);
        args.putString(ARG_PARAM8, mercBusinessId);
        args.putBoolean(ARG_PARAM9, isOrderStockInEnter);
        args.putString(ARG_PARAM10, orderId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            typeiId= getArguments().getString(ARG_PARAM1);
            businessId= getArguments().getString(ARG_PARAM2);
            businessName= getArguments().getString(ARG_PARAM3);/*最上名称*/
            mChageData= getArguments().getParcelableArrayList(ARG_PARAM4);
            isValuationEnter= getArguments().getBoolean(Constant.ARG_PARAM5,false);
            userId= getArguments().getString(ARG_PARAM6);
            isStorageEnter= getArguments().getBoolean(ARG_PARAM7,false);
            mercBusinessId= getArguments().getString(ARG_PARAM8);
            isOrderStockInEnter= getArguments().getBoolean(ARG_PARAM9,false);
            orderId= getArguments().getString(ARG_PARAM10);

        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
         view = inflater.inflate(R.layout.fragment_shopp_list_fragment_child, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initView() {
        List<ShoppingBean> mDate = new ArrayList();
        GridItemDecoration divider = new GridItemDecoration.Builder(_mActivity)
                .setHorizontal(R.dimen.default_divider_5dp)
                .setVertical(R.dimen.default_divider_5dp)
                .setColorResource(R.color.transparent)
                .build();
         mEmptyView= view.findViewById(R.id.empty_view);
      //  recyclerViews.setEmptyView(mEmptyView);//设置在setAdapter之前才能生效
        initGridRecyclerView(recyclerViews, 3);
        mShoppListAdapter= new ShoppListAdapter(_mActivity, mDate);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mShoppListAdapter);
        recyclerViews.setAdapter(mLRecyclerViewAdapter);
        recyclerViews.addItemDecoration(divider);
        ((SimpleItemAnimator)recyclerViews.getItemAnimator()).setSupportsChangeAnimations(false);/*修复闪屏*/
        recyclerViews.setPullRefreshEnabled(false);



    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();

        if (!isloadFinish){
            requestData();
        }

    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(ShoppChildEvent event) {
        switch (event.getMessage()) {
            case ADD_COUNT:/*添加*/


                mShoppListAdapter.notifyDataSetChanged();
                break;
            case SUBTRACT_COUNT: /*减少*/

                mShoppListAdapter.notifyDataSetChanged();
                break;
            case CLEAR_ALL: /*清除全部*/

                for (ShoppingBean item : mShoppListAdapter.getDataList()) {
                    item.setCount(0);
                }
                mShoppListAdapter.notifyDataSetChanged();
                break;
        }
    }
    /**
     * 获取数据列表
     */
    private   void  requestData(){
        showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        if (!CheckUtils.isEmpty(orderId)) {
            mHashMap.put("orderId",orderId); /*订单id*/
        }
        mHashMap.put("userId",userId); /*用户Id*/
        mHashMap.put("businessId",businessId); /*Tab id */
        mHashMap.put("typeId",typeiId);
        mHashMap.put("accessToken", SaveParams.getToken());
        L.i("mHashMap="+mHashMap.toString());
        addSubscription(apiStores().pricelist(Constant.createParameter(mHashMap)),
                new ApiCallback<ShoppingBean>() {
                    @Override
                    public void onSuccess( ShoppingBean model) {

                        if (model.getHttpCode() == 200) {
                            fillData(model);

                        } else {

                            T.show(model.getMsg());

                        }

                    }


                    @Override
                    public void onFinish() {

                        dismissProgressDialog();

                    }
                });


    }

    private void fillData(ShoppingBean model) {
        isloadFinish=true;
        List<ShoppingBean> mClothData = model.getData();
        mEmptyView.setVisibility(CheckUtils.isEmpty(mClothData)?View.VISIBLE:View.GONE);
        if (!CheckUtils.isEmpty(mChageData)&&!CheckUtils.isEmpty(mClothData)){
            for (ShoppingBean item : mClothData) {
                String id = item.getId();
                for (ShoppingBean parcelable : mChageData) {
                    if (isOrderStockInEnter && CheckUtils.isEmpty(parcelable.getSelectServiceName()))
                        return;
                    if (id.equals(parcelable.getId())) {
                        item.setMercBusinessId(isOrderStockInEnter?mercBusinessId:"");
                        item.setCount(parcelable.getCount());
                        item.setSaleType(0);
                        item.setDiscount(parcelable.getDiscount());
                        item.setSelectServiceId(parcelable.getSelectServiceId());
                        item.setSelectServiceName(parcelable.getSelectServiceName());
                        ShoppEvent.postHasData(ShoppEvent.Message.CHAGE_ADD_COUNT, item);


                    }
                }

            }
        }
        mShoppListAdapter.setDataList(mClothData);
    }


    @Override
    protected void initListener() {
        super.initListener();
        mLRecyclerViewAdapter.setOnItemClickListener(mOnItemClickListener);
    }

    private OnItemClickListener  mOnItemClickListener=new OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            ShoppingBean mitem = mShoppListAdapter.getDataList().get(position);
            mitem.setBusinessName(businessName);
            mitem.setMercBusinessId(mercBusinessId);

            if (isValuationEnter&&!CheckUtils.isEmpty(mitem.getServiceList())){
                showServeDialog(position,mitem);
            }else if (isStorageEnter&&!CheckUtils.isEmpty(mitem.getServiceList())){
                showServeDialog(position,mitem);
            }else if (!isStorageEnter&&!isOrderStockInEnter){
                mitem.setCount(mitem.getCount()+1);
                mShoppListAdapter.notifyItemChanged(position);
                ShoppEvent.postHasData(ShoppEvent.Message.ADD_COUNT,mitem);
            }



        }
    };

  public   void showServeDialog(int position, ShoppingBean mitem) {
        ServeCarDialogFragment   mServeCarDialog=ServeCarDialogFragment.newInstance(mitem,position);
        mServeCarDialog.setOnSubmitClickListener(mDialogSubmit);
        mServeCarDialog.show(getChildFragmentManager(),ServeCarDialogFragment.class.getName());
    }

    private DialogSubmitListener  mDialogSubmit=new DialogSubmitListener() {
        @Override
        public void onSubmitClick(int parent, Object message) {
            mShoppListAdapter.notifyItemChanged((int)message);
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

}
